<?php

App::uses('AppModel', 'Model');

class Product extends AppModel {

    public $table = 'products';
    public $actsAs = array('CakePtbr.AjusteData', 'CakePtbr.AjusteFloat', 'Search.Searchable');
    public $filterArgs = array(
        'id' => array('type' => 'value'),
        'category_id' => array('type' => 'value'),
        'brand_id' => array('type' => 'value'),
        'name' => array('type' => 'like'),
        'slug' => array('type' => 'like'),
        'description' => array('type' => 'like'),
        'image' => array('type' => 'like'),
        'price' => array('type' => 'like'),
        'weight' => array('type' => 'like'),
        'tags' => array('type' => 'like'),
        'views' => array('type' => 'value'),
        'active' => array('type' => 'value'),
        'created' => array('type' => 'like'),
        'modified' => array('type' => 'like'),
        'search' => array(
            'type' => 'like',
            'field' => 'Product.name'
        )
    );
    public $validate = array(
        'name' => array(
            'rule1' => array(
                'rule' => array('between', 3, 60),
                'message' => 'Name is required',
                'allowEmpty' => false,
                'required' => false,
            ),
            'rule2' => array(
                'rule' => array('isUnique'),
                'message' => 'Name already exists',
                'allowEmpty' => false,
                'required' => false,
            ),
        ),
        'slug' => array(
            'rule1' => array(
                'rule' => array('between', 3, 50),
                'message' => "Rota obrigatoria",
                'allowEmpty' => false,
                'required' => false,
            ),
            'rule2' => array(
                'rule' => '/^[a-z0-9\-]{3,50}$/',
                'message' => "Somente letras minúsculas, numeros e traços, entre 3-50 caracteres",
                'allowEmpty' => false,
                'required' => false,
            ),
            'rule3' => array(
                'rule' => array('isUnique'),
                'message' => "Rota já existe",
                'allowEmpty' => false,
                'required' => false,
            ),
        ),
        'price' => array(
            'notempty' => array(
                'rule' => array('decimal'),
                'message' => 'Valor invalido',
                'allowEmpty' => false,
                'required' => true,
                //'last' => false, // Stop validation after this rule
                'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
        'weight' => array(
            'notempty' => array(
                'rule' => array('decimal'),
                'message' => 'Peso invalido',
                'allowEmpty' => false,
                'required' => true,
                //'last' => false, // Stop validation after this rule
                'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
    );
    public $belongsTo = array(
        'Category' => array(
            'className' => 'Category',
            'foreignKey' => 'category_id',
            'conditions' => '',
            'fields' => '',
            'order' => '',
        ),
        'Brand' => array(
            'className' => 'Brand',
            'foreignKey' => 'brand_id',
            'conditions' => '',
            'fields' => '',
            'order' => '',
        ),
    );
    public $hasMany = array(
        'Productmod',
        'ProductsImage'
    );

    public function updateViews($products) {

        if (!isset($products[0])) {
            $a = $products;
            unset($products);
            $products[0] = $a;
        }

        $this->unbindModel(
                array('belongsTo' => array('Category', 'Brand'))
        );

        $productIds = Set::extract('/Product/id', $products);

        $this->updateAll(
                array(
            'Product.views' => 'Product.views + 1',
                ), array('Product.id' => $productIds)
        );
    }

    public function afterSave($created, $options = array()) {
        if (isset($this->data['ProductsImage']['id']) AND count($this->data['ProductsImage']['id']) > 0) {
            $ProductsImage = ClassRegistry::init('ProductsImage');
            foreach ($this->data['ProductsImage']['id'] as $key => $value) {
                if ($value['error'] === 0) {
                    $ext = explode('/', $value['type']);
                    $name = md5(time() . $value['name']) . '.' . $ext[1];
                    if (copy($value['tmp_name'], APP . WEBROOT_DIR . '/images/' . $name)) {
                        $dados = array(
                            'product_id' => $this->data['Product']['id'],
                            'active' => 1,
                            'image' => $name,
                        );
                        $ProductsImage->save(array('ProductsImage' => $dados));
                        $ProductsImage->clear();
                    }
                }
            }
        }
        return parent::afterSave($created, $options);
    }

}
